<template>
  <div>
  <el-container>
    <el-header>
      <span>项目编号：&nbsp;</span>
      <span>{{this.$route.query.projectCode}}</span>
      &nbsp;
      <span>项目名称：&nbsp;</span>
      <span>{{this.$route.query.projectName}}</span>
      &nbsp;
      <span>采购类别：&nbsp;</span>
      <span>{{this.$route.query.purchaseCategoryName}}</span>
      &nbsp;
      <span>预算金额：&nbsp;</span>
      <span>{{this.$route.query.budget}}</span>
      <span>元</span>
      <el-button :disabled="isDisabled" class="button" type="primary" @click="addnew()" >新建</el-button> &nbsp;

    </el-header>

    <el-main>
      <el-table
          :data="tableData"
          border
          style="width: 965px">
        <el-table-column
            prop="flag"
            label="成交供应商"
            width="120">
        </el-table-column>
        <el-table-column
            prop="supplierName"
            label="供应商名称"
            width="130">
        </el-table-column>
        <el-table-column
            prop="price"
            label="报价(元)"
            width="140">
        </el-table-column>
        <el-table-column
            prop="priceRanking"
            label="报价排名"
            width="140">
        </el-table-column>
        <el-table-column
            prop="remark"
            label="备注"
            width="130">
        </el-table-column>
        <el-table-column
            prop="fileName"
            label="报价文件"
            width="130">
          <template slot-scope="{row}">
            <!-- 给单元格内容添加点击事件 -->
            <span @click="downloadquotatiton(row)" style="color: #409eff" >{{ row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="173">
          <template slot-scope="scope">
            <el-button :disabled="isDisabled" @click="handleEdit(scope.$index,scope.row)" type="text" size="small">修改</el-button>
            <el-button  type="text" size="small" @click="downloadquotatiton(scope.row)">下载</el-button>
            <el-button :disabled="isDisabled" type="text" size="small" @click="deletequotatiton(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="status">
        <p>提交状态：{{this.project.supplyerSubmitStatus}}  提交时间：{{this.project.supplyerSubmitTime }}</p>
        <p>审批状态：{{this.project.supplyerApproveStatus}}  审批时间：{{this.project.supplyerApproveTime}}</p>
      </div>
    </el-main>

    <el-footer>

      <el-button :disabled="isDisabled" type="primary" @click="submitApproval">成交供应商确认提交审批</el-button>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="primary" @click="goBack">返回</el-button>
    </el-footer>
  </el-container>
  <el-dialog title="新建" :visible.sync="dialogFormVisible">
    <el-form :model="addform" ref="addform">
      <el-form-item label="供应商名称" >

        <el-select v-model="addform.supplierName"  placeholder="请选择" @click.native="handleSelectChange" >
          <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item"
              >
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="报价" >
        <el-input v-model="addform.price" autocomplete="off" type="number"    placeholder="请输入内容" style="width: 300px;position: relative;left:28px" @input="handleInput1"></el-input><div style="float: left;position: relative;left:350px">元</div>
      </el-form-item>

      <el-form-item label="报价文件" >

<!--        <el-input type="primary" v-model="fileName1" placeholder="请选择文件" readonly style="width: 300px;position: relative;left:15px"></el-input>-->

        <el-upload
            ref="fileupload1"
            action=""
            accept=".pdf"
            :on-change="handleChange1"
            :auto-upload="false"
            :multiple="false"
            :file-list="filelist1"
        >
          <el-button size="small" type="primary" style="position: relative;left:17px">选择文件</el-button>
        </el-upload>
        <el-progress v-if="ishide1"  :percentage="percent1" style="width: 500px"></el-progress>
      </el-form-item>

      <el-form-item label="备注" >
        <el-input v-model="addform.remark" autocomplete="off" type="textarea" :rows="2"   placeholder="请输入内容" style="width: 300px;position: relative;left:41px"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="addquotation">确 定</el-button>
      <el-button @click="dialogFormVisible = false">取 消</el-button>
    </div>

  </el-dialog>

    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editform" ref="editform">
        <el-form-item label="供应商名称" >

          <el-select v-model="editform.supplierName"  placeholder="请选择" @click.native="handleSelectChange" >
            <el-option
                v-for="item in options"
                :key="item"
                :label="item"
                :value="item"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="报价" >
          <el-input v-model="editform.price" autocomplete="off" type="number" @input="handleInput2"   placeholder="请输入内容" style="width: 300px;position: relative;left:28px"></el-input><div style="float: left;position: relative;left:350px">元</div>
        </el-form-item>

        <el-form-item label="报价文件" >
          <el-input type="primary" v-model="editform.fileName" placeholder='请选择文件' readonly style="width: 300px;position: relative;left:15px"></el-input>
          <el-upload
              ref="fileupload2"
              action=""
              accept=".pdf"
              :on-change="handleChange2"
              :auto-upload="false"
              :multiple="false"
              :file-list="filelist2"
          >
            <el-button size="small" type="primary" style="position: relative;left:85px">选择文件</el-button>
          </el-upload>
          <el-progress v-if="ishide2"  :percentage="percent2" style="width: 500px"></el-progress>
        </el-form-item>

        <el-form-item label="备注" >
          <el-input v-model="editform.remark" autocomplete="off" type="textarea" :rows="2"   placeholder="请输入内容" style="width: 300px;position: relative;left:41px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editquotation">确 定</el-button>
        <el-button @click="editFormVisible = false">取 消</el-button>
      </div>

    </el-dialog>
  </div>

</template>

<script>
import request from "@/utils/request";
import {MessageBox} from "element-ui";
import Vue from "vue";
Vue.prototype.$confirm = MessageBox.confirm
export default {
  name: "index",
  created() {
    this.onload()
  },
  methods:{
    handleInput1(){
      this.addform.price=this.addform.price.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    },
    handleInput2(){
      this.editform.price=this.editform.price.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    },
    handleSelectChange(){
      console.log(this.options)
      if(this.options.length===0){
        this.$message({
          message: "该项目尚未添加潜在供应商或所有供应商均已添加报价",
        });
        return;
      }
      return;
    },
    async onload(){
      let data={}
      data['projectId']=this.$route.query['projectId']
      let res=await request(
          {
            url: "/ContractSupplierQuotation/manage",
            method: "post",
            data:data
          }
      )
      console.log(res.data.data)
      console.log(this.$route.query)
      this.tableData=res.data.data.quotations
      this.options=res.data.data.suppliers
      this.project=res.data.data.project
      if(this.project.supplyerSubmitStatus==="已提交") {
        this.isDisabled=true;
      }
    },
    addnew(){
      this.dialogFormVisible=true
      this.addform={
            "supplierName": '',
            "price": '',
            "fileuploadStatus": "失败",
            "fileName":"",
            "filePath": "",
            "projectId": '',
            "remark": '',
      }
      this.filelist1=[]
      this.file1=null
    },
    async deletequotatiton(index,row){
        const confirmResult =  await  this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          // 指定确认按钮的文本
          confirmButtonText: '确定',
          //指定取消按钮的文本
          cancelButtonText: '取消',
          //通过type指定提示信息前面的小图标
          type: 'warning'
        }).catch(err=>{
          // 这个捕获一下错误，要不然我们点击“取消”按钮之后控制台会报错
          return err
        })
        // console.log(confirmResult)

        if(confirmResult !=='confirm'){
          // 说明用户不想删除
          return this.$message.info('已取消删除')
        }

        //  console.log('确认删除')
        let data = {}
        data['id'] = row.id //等号右边的值需要修改
        let res = await request(
            {
              url: "/ContractSupplierQuotation/deletequatation",
              method: "post",
              data: data
            }
        )
      if(res.data.code===200){
        this.$message({
          message:"删除成功",
          type:"success"
        })
      }else {
        this.$message({
          message:"删除失败",
          type:"error"
        })
      }
      await this.onload();
      },
    async downloadquotatiton( row){
      let data={
        'filePath':row.filePath,
        'fileName':row.fileName
      }
      let res=await request(
          {
            url: "/ContractSupplierQuotation/filedownload",
            method: "post",
            responseType: 'blob',
            data:data
          }
      )
      console.log(res.data)
      let blob = new Blob([res.data], {type: 'application/octet-stream'})
      // 创建一个临时的URL，用于下载文件
      let url = window.URL.createObjectURL(blob)
      // 创建一个a标签，指定下载链接和文件名
      let link = document.createElement('a')
      link.href = url
      link.download = row.fileName // 这里可以根据实际情况指定文件名和扩展名
      // 触发a标签的点击事件，开始下载文件
      link.click()
      // 释放URL资源
      window.URL.revokeObjectURL(url)
    },



    async addquotation(){
        if(this.addform.supplierName===null||this.addform.supplierName===''){
          this.$message({
            message: "供应商名称为空不能进行增加或修改",
          })
        }else if (this.addform.price<=0){
          this.$message({
            message:"供应商报价必须大于0"
          })
        }else if( parseFloat(this.addform.price) >this.$route.query.budget){
          this.$message({
            message:"供应商报价不能超出预算金额"
          })
        }else if(this.file1===null){
          this.$message({
            message:"请先选择报价文件"
          })
          return
        }
        // else if(this.file1===null){
        //   let data = {
        //     "supplierName": this.addform.supplierName,
        //     "price": this.addform.price,
        //     "fileuploadStatus": "失败",
        //     "projectId": this.$route.query.projectId,
        //     "fileName": this.fileName1,
        //     "filePath": this.addform.filePath,
        //     "remark": this.addform.remark
        //   }
        //   let res = await request(
        //       {
        //         url: "/ContractSupplierQuotation/addquatation",
        //         method: "post",
        //         data: data,
        //
        //       }
        //   )
        //   if(res.data.code===114513){
        //     this.$message({
        //       message:res.data.msg
        //     })
        //     return
        //   }
        //   this.dialogFormVisible=false;
        //   location.reload();
        // }
        else{
          await this.fileupload1()
          console.log(this.addform.fileuploadStatus)
          if (this.addform.fileuploadStatus === '成功') {
              console.log('1')
              let data = {
                "supplierName": this.addform.supplierName,
                "price": this.addform.price,
                "fileuploadStatus": "成功",
                "projectId": this.$route.query.projectId,
                "fileName": this.fileName1,
                "filePath": this.addform.filePath,
                "remark": this.addform.remark
              }
              let res = await request(
                  {
                    url: "/ContractSupplierQuotation/addquatation",
                    method: "post",
                    data: data,
                  }
              )
              if(res.data.code===114513){
                this.$message({
                  message:res.data.msg
                })
                return
              }
              if(res.data.code===200){
                this.$message({
                  message:"添加成功",
                  type:"success"
                })
              }
              this.dialogFormVisible=false;
              await this.onload();
            } else {
              return
            }
        }
      },
    async submitApproval(){
        if(this.tableData.length>=3) {
          let data = {}
          data['projectId'] = this.$route.query['projectId']
          let res = await request(
              {
                url: "/ContractSupplierQuotation/approval",
                method: "post",
                data: data
              }
          )
          if(this.supplyerSubmitStatus==='已提交')
          {
            this.isDisabled=true
          }
          this.$message({
            message: '提交审批成功',
            type: 'success'
          });
          await this.onload();
        }
        else{
          this.$message({
            message: '至少应添加3个供应商报价才能提交审批',
          });
        }
      },

    handleEdit(index,row){
      this.editFormVisible = true;
      this.editform.supplierName = row.supplierName
      this.editform.price = row.price
      this.editform.fileName = row.fileName
      this.editform.remark = row.remark
      this.editform.filePath = row.filePath
      this.editform.id = row.id
      this.filelist2=[]
      this.file2=null
      },
    async fileupload2(){
      if(this.file2.name.substring(this.file2.name.lastIndexOf('.')+1)!='pdf'){
        console.log("file1",this.file1.name.substring(this.file1.name.lastIndexOf('.')+1))
        this.filelist2=[]
        this.file2=null;
        this.ishide2=false;
        this.$message({
          type:"warning",
          message:"仅能上传pdf文件！"
        })
        return
      }
      let formData = new FormData();
      let that=this
      formData.append('supplierName',that.editform.supplierName)
      formData.append('uploadfile',that.file2.raw)
      formData.append('projectId',that.$route.query.projectId)
      console.log('file',formData.get('uploadfile'))
      let res=await request({
        url: "/ContractSupplierQuotation/fileupload",
        method: "post",
        data:formData,
        onUploadProgress: progressEvent => {
          this.ishide2 = true
          let process = (progressEvent.loaded / progressEvent.total * 100 | 0)
          this.percent2=process
        }
      })
      console.log(res)
      if(res.data.code===200){
        this.editform.fileuploadStatus='成功'
        this.editform.fileName=res.data.data.fileName
        this.editform.filePath=res.data.data.filePath
      }else {
        this.$message({
          message:'文件上传失败',
          type:'error'
        })
      }
      this.ishide2=false
      this.percent2=0
      console.log('editform',this.editform)
    },

    async editquotation(){
      if(this.editform.supplierName===null||this.editform.supplierName===''){
        this.$message({
          message: "供应商名称为空不能进行增加或修改",
        })
      }else if (this.editform.price<=0){
        this.$message({
          message:"供应商报价必须大于0"
        })
      }else if( parseFloat(this.editform.price) > this.$route.query.budget){
        this.$message({
          message:"供应商报价不能超出预算金额"
        })
      }
      else {
        if (this.file2!=null) {
          await this.fileupload2()
          if(this.editform.fileuploadStatus==='失败'){
            return
          }
          let data = {
            "supplierName": this.editform.supplierName,
            "price": this.editform.price,
            "fileuploadStatus": "成功",
            "id": this.editform.id,
            "projectId": this.$route.query.projectId,
            "fileName": this.editform.fileName,
            "filePath": this.editform.filePath,
            "remark": this.editform.remark
          }
          let res = await request(
              {
                url: "/ContractSupplierQuotation/editquatation",
                method: "post",
                data: data
              }
          )
          if(res.data.code===114513){
            this.$message({
              message:'存在相同报价，请修改',
              type:'error'
            })
            return
          }
          if(res.data.code===200){
            this.$message({
              message:"修改成功",
              type:"success"
            })
          }
          this.editFormVisible = false;
          await this.onload();
        } else {
          let data = {
            "supplierName": this.editform.supplierName,
            "price": this.editform.price,
            "fileuploadStatus": this.editform.fileuploadStatus,
            "id": this.editform.id,
            "projectId": this.$route.query.projectId,
            "fileName": this.editform.fileName,
            "filePath": this.editform.filePath,
            "remark": this.editform.remark
          }
          let res = await request(
              {
                url: "/ContractSupplierQuotation/editquatation",
                method: "post",
                data: data
              }
          )
          if(res.data.code===114513){
            this.$message({
              message:'存在相同报价，请修改',
              type:'error'
            })
            return
          }
          if(res.data.code===200){
            this.$message({
              message:"修改成功",
              type:"success"
            })
          }
          this.editFormVisible = false;
          await this.onload();
        }
      }
    },

    goBack(){
      this.$router.go(-1)
    },
    handleChange1(file) {
      this.fileName1 = file.name;
      this.file1=file
      this.filelist1=[]
      this.filelist1[0]=file
    },
    handleChange2(file) {
      this.fileName2 = file.name;
      this.editform.fileName = file.name;
      this.file2=file
      this.filelist2=[]
      this.filelist2[0]=file
    },
    async fileupload1(){
      if (this.file1===null){
        return
      }
      if(this.file1.name.substring(this.file1.name.lastIndexOf('.')+1)!='pdf'){
        console.log("file1",this.file1.name.substring(this.file1.name.lastIndexOf('.')+1))
        this.filelist1=[]
        this.file1=null;
        this.ishide1=false;
        this.$message({
          type:"warning",
          message:"仅能上传pdf文件！"
        })
        return
      }
      let formData = new FormData();
      let that=this
      formData.append('supplierName',that.addform.supplierName)
      formData.append('uploadfile',that.file1.raw)
      formData.append('projectId',that.$route.query.projectId)
      console.log('file',formData.get('uploadfile'))
      let res=await request({
        url: "/ContractSupplierQuotation/fileupload",
        method: "post",
        data:formData,
        onUploadProgress: progressEvent => {
          this.ishide1 = true
          let process = (progressEvent.loaded / progressEvent.total * 100 | 0)
          this.percent1=process
          console.log("ing")

        }
      })
      this.ishide1=false
      this.percent1=0
      console.log(res)
      if(res.data.code===200){
          this.addform.fileuploadStatus='成功'
          this.addform.fileName=res.data.data.fileName
        this.fileName1=res.data.data.fileName
          this.addform.filePath=res.data.data.filePath
      }else {
        this.$message({
          message:'文件上传失败',
          type:'error'
        })
      }
      console.log('addform',this.addform)
    }

  },



  data() {

    return {
      supplyerSubmitStatus:'未提交',
      isDisabled:false,
      //修改的时候进度条百分比
      percent2:0,
      //添加的时候进度条百分比
      percent1:0,
      //修改的时候进度条是否隐藏
      ishide2:false,
      //添加的时候进度条是否隐藏
      ishide1:false,
      dialogFormVisible: false,
      editFormVisible:false,
      tableData: [],
      project:{},
      file1:null,
      file2:null,
      filelist1:[],
      filelist2:[],
      fileName1: "",
      fileName2: '',// 上传的文件名
      options:[],
      addform:{
        "supplierName": '',
        "price": '',
        "fileuploadStatus": "失败",
        "fileName":"",
        "filePath": "",
        "projectId": '',
        "remark": '',
      },
      editform:{
        "supplierName": '',
        "price": '',
        "fileuploadStatus": "失败",
        "fileName":"",
        "filePath": "",
        "id":"",
        "projectId": '',
        "remark": '',
      },

    }
  }
}
</script>

<style scoped>
.el-header {
  background-color:rgb(255,255,255);
  color: #333;
  line-height: 80px;
}
.button{
  position: relative;
  left: 20px ;
}
.el-footer{
  background-color: rgb(255,255,255);
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-main {
  background-color: rgb(255,255,255);
  color: #333;
  text-align: center;
  line-height: 60px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
.status{
  /*float: left;*/
  font-size: 15px;
  text-align:left;
}
</style>
